<?php

namespace app\controller\admin;

use app\base\BaseEncryptController;
use app\libs\Util;
use app\model\goods\GoodsModel;
use app\model\goods\GoodsTypeModel;
use think\Request;
use app\factory\GoodsType as GoodsTypeFactory;

/**
 * GoodsType 商品分类
 * Class GoodsType
 * @package app\controller
 */
class GoodsType extends BaseEncryptController
{
    protected function initialize()
    {
        parent::initialize();
        $this->model = new GoodsTypeModel();
    }

    /**
     * 层级列表
     * @param Request $request
     * @return \think\response\Json
     */
    public function getTree(Request $request)
    {
        $map = [];
        $status = $request->param('status');
        $special = $request->param('special');
        if (intval($status) != -1) {
            $map[] = ['status', '=', $status];
        }
        if (intval($special) != -1) {
            $map[] = ['special', '=', $special];
        }
        $list = $this->model->where($map)->select();
        $tree = Util::levelTreeChildren($list, 0);
        Util::listOrder($tree, 'sort', 'desc', 'number');
        return self::returnMsg(1, ['treeData' => $tree]);
    }

    /**
     * 获取单条数据
     * @param string $id
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getInfo($id = '')
    {
        $data = $this->model->getInfo($id);
        return self::returnMsg(1, $data);
    }

    /**
     * 修改
     * @param Request $request
     * @return \think\response\Json
     */
    public function onEdit(Request $request)
    {
        $formData = [
            "name" => $request->param("name"),
            "img" => $request->param("img"),
            "sort" => $request->param("sort"),
            "status" => $request->param("status"),
            "id" => $request->param("id"),//id
            "special" => $request->param("special"),//是否是敏感
            "go_up" => $request->param("go_up"),//上涨价格
        ];

        $validate = 'app\validate\GoodsTypeValidate.Update';
        $result = $this->validate($formData, $validate);
        if (true !== $result) {
            return self::returnMsg(991, [], $result);
        } else {
            $ret = $this->model->saveData($formData, false, false);//修改是否添加进缓存。。。
            if (false !== $ret['flag']) {
                return self::returnMsg(1);
            } else {
                return self::returnMsg(0);
            }
        }
    }

    /**
     * 添加子分类
     * @param Request $request
     * @return \think\response\Json
     */
    public function onAdd(Request $request)
    {
        $formData = [
            "id" => $request->param("id"),//id
            "name" => $request->param("name"),
            "img" => $request->param("img"),
            "status" => $request->param("status"),
            "sort" => $request->param("sort"),
            "parent_id" => $request->param("parent_id"),//id等于父级
            "special" => $request->param("special"),//是否是敏感
            "go_up" => $request->param("go_up"),//是否是敏感
        ];
        if (empty($formData['id'])) {
            $validate = 'app\validate\GoodsTypeValidate.Add';
        } else {
            $validate = 'app\validate\GoodsTypeValidate.Update';
        }
        $result = $this->validate($formData, $validate);
        if (true !== $result) {
            return self::returnMsg(991, [], $result);
        } else {
            $ret = $this->model->saveData($formData, false, false);//修改是否添加进缓存。。。
            if (false !== $ret['flag']) {
                return self::returnMsg(1);
            } else {
                return self::returnMsg(0);
            }
        }
    }

    /**
     * 上线状态
     * @param Request $request
     * @return \think\response\Json
     */
    public function onStatus(Request $request)
    {
        $formData = [
            'id' => $request->param('id'),
            'status' => $request->param('status'),
        ];
        if (is_array($formData['id'])) {
            $list = [];
            foreach ($formData['id'] as $key => $value) {
                $list[] = ['id' => $value, 'status' => $formData['status']];
            }
            $ret = $this->model->saveAll($list);
            if ($ret) {
                return self::returnMsg(1);
            } else {
                return self::returnMsg(0);
            }
        } else {
            $validate = 'app\validate\GoodsTypeValidate.upstatus';
            $result = $this->validate($formData, $validate);
            if (true !== $result) {
                return self::returnMsg(991, [], $result);
            } else {
                $child_ids = $this->model->getChildId($formData['id']);
                if (is_array($child_ids)) {
                    $list = [];
                    foreach ($child_ids as $key => $value) {
                        $list[] = ['id' => $value, 'status' => $formData['status']];
                    }
                    $ret = $this->model->saveAll($list);
                    if ($ret) {
                        return self::returnMsg(1);
                    } else {
                        return self::returnMsg(0);
                    }
                }
                $ret = $this->model->saveData($formData, false, false);
                if (false !== $ret['flag']) {
                    return self::returnMsg(1);
                } else {
                    return self::returnMsg(0);
                }
            }
        }
    }

    /**
     * 删除
     * @param $id
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function onDelete($id)
    {
        $goods_model = new GoodsModel();
        $ret = $goods_model->where('goods_type_id', $id)->find();
        if (!empty($ret)) {
            return self::returnMsg(0, [], '该分类下有商品不能删除');
        }
        $ret = $this->model->where('parent_id', $id)->find();
        if (!empty($ret)) {
            return self::returnMsg(0, [], '该分类下有子分类不能删除');
        }
        $flag = $this->model::destroy(['id' => $id]);
        if (false !== $flag) {
            $this->model->delRedis($id);
            $this->model->redis->zRem($this->model->redis_key . ':rank', $id);
            $this->model->addToRecycle($id, 'GoodsTypeModel', '商品分类管理', $this->currentUser['user_id'], $this->currentUser['user_type'], 'goods');
            return self::returnMsg(1);
        } else {
            return self::returnMsg(1002);
        }
    }

    /**
     * 分类信息
     * @param $type
     * @return \think\response\Json
     */
    public function getTypedata()
    {
        $field = "id,name,img,parent_id,sort";
        $map = [
            'status' => 0
        ];
        $data = $this->model->getAll($map, $field);
        $list = Util::levelTreeChildren($data, 0);
        Util::listOrder($list, 'sort', 'desc', 'number');
        $listIds = Util::getChildrenIds($list);
        $out_list = [];
        $GoodsModel = new GoodsModel();
        foreach ($listIds as $key => $value) {
            $map_temp = [
                'goods_status' => 1,
                'whereIn' => [
                    'field' => 'goods_type_id',
                    'condition' => $value['ids_str'],
                ]
            ];
            $res = $GoodsModel->getListIn($map_temp, "id DESC", 1000, 'id,goods_title,goods_img,goods_bazaar_price,goods_original_price');
            $out_list[$key]['goodslist'] = $res;
            $out_list[$key]['title'] = $value['title'];
        }
        return self::returnMsg(1, $out_list);
    }
}
